package cn.play.cardgame.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

import java.util.LinkedList;
import java.util.Random;

import cn.play.cardgame.util.NumUtil;

public class ScrollNumber extends TextView {
	// 每秒刷新多少次
	private static final int COUNTPERS = 100;

	public ScrollNumber(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public ScrollNumber(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public ScrollNumber(Context context) {
		this(context, null);
	}

	public void startAnim(float num) {
		startAnim(num, 500);
	}

	public void startAnim(float num, long time) {
		if (num == 0) {
			setText(NumUtil.NumberFormat(num, 0));
			return;
		}

		Float[] nums = splitNum(num, (int) ((time / 1000f) * COUNTPERS), 100);

		Counter counter = new Counter(this, nums, time);

		this.removeCallbacks(counter);
		this.post(counter);
	}

	private Float[] splitNum(float num, int count, float start) {
		Random random = new Random(System.currentTimeMillis());
		float temp = num;
		float sum = start;
		LinkedList<Float> nums = new LinkedList<Float>();
		nums.add(start);
		while (true) {
			float nextFloat = NumUtil.NumberFormatFloat((random.nextFloat()
					* num * 2f)
					/ (float) count, 0);
			if (temp - nextFloat - start >= 0) {
				sum = NumUtil.NumberFormatFloat(sum + nextFloat, 0);
				nums.add(sum);
				temp -= nextFloat;
			} else {
				nums.add(num);
				return nums.toArray(new Float[0]);
			}
		}
	}

	class Counter implements Runnable {

		private final TextView view;
		private Float[] nums;
		private long pertime;

		private int i = 0;

		Counter(TextView view, Float[] nums, long time) {
			this.view = view;
			this.nums = nums;
			this.pertime = time / nums.length;
		}

		@Override
		public void run() {
			if (i > nums.length - 1) {
				view.removeCallbacks(Counter.this);
				return;
			}
			view.setText(NumUtil.NumberFormat(nums[i++], 0));
			view.removeCallbacks(Counter.this);
			view.postDelayed(Counter.this, pertime);
		}
	}
}
